'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { trpc } from '@/lib/trpc-provider'
import { copyToClipboard } from '@/lib/utils'
import { Copy, RefreshCw, Download } from 'lucide-react'

export default function UuidGeneratorPage() {
  const [uuids, setUuids] = useState<string[]>([])
  const [version, setVersion] = useState<'v1' | 'v4'>('v4')
  const [count, setCount] = useState(1)
  const [copySuccess, setCopySuccess] = useState<{ [key: string]: boolean }>({})
  const [copyAllSuccess, setCopyAllSuccess] = useState(false)

  const generateMutation = trpc.tools.generateUuid.useMutation({
    onSuccess: (data) => {
      if (data.success && data.uuids) {
        setUuids(data.uuids)
      }
    }
  })

  const handleGenerate = () => {
    // Generate UUIDs in a single request
    generateMutation.mutate({ version, count })
  }

  const handleCopy = async (uuid: string, index: number) => {
    const success = await copyToClipboard(uuid)
    if (success) {
      setCopySuccess(prev => ({ ...prev, [index]: true }))
      setTimeout(() => {
        setCopySuccess(prev => ({ ...prev, [index]: false }))
      }, 2000)
    }
  }

  const handleCopyAll = async () => {
    if (uuids.length > 0) {
      const allUuids = uuids.join('\n')
      const success = await copyToClipboard(allUuids)
      if (success) {
        setCopyAllSuccess(true)
        setTimeout(() => setCopyAllSuccess(false), 2000)
      }
    }
  }

  const handleDownload = () => {
    if (uuids.length > 0) {
      const content = uuids.join('\n')
      const blob = new Blob([content], { type: 'text/plain' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `uuids-${version}-${new Date().toISOString().split('T')[0]}.txt`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  }

  const handleClear = () => {
    setUuids([])
    setCopySuccess({})
    setCopyAllSuccess(false)
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            UUID 生成器
          </h1>
          <p className="text-gray-600">
            生成唯一标识符（UUID），支持 v1 和 v4 版本
          </p>
        </div>

        {/* Controls */}
        <div className="bg-white p-6 rounded-lg border border-gray-200 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            {/* Version Selector */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                UUID 版本
              </label>
              <select 
                value={version} 
                onChange={(e) => setVersion(e.target.value as 'v1' | 'v4')}
                className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="v4">Version 4 (随机)</option>
                <option value="v1">Version 1 (时间戳)</option>
              </select>
            </div>

            {/* Count Selector */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                生成数量
              </label>
              <select 
                value={count} 
                onChange={(e) => setCount(Number(e.target.value))}
                className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value={1}>1 个</option>
                <option value={5}>5 个</option>
                <option value={10}>10 个</option>
                <option value={20}>20 个</option>
                <option value={50}>50 个</option>
              </select>
            </div>

            {/* Generate Button */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                操作
              </label>
              <Button 
                onClick={handleGenerate} 
                disabled={generateMutation.isLoading}
                className="w-full"
              >
                <RefreshCw className={`w-4 h-4 mr-2 ${generateMutation.isLoading ? 'animate-spin' : ''}`} />
                {generateMutation.isLoading ? '生成中...' : '生成 UUID'}
              </Button>
            </div>
          </div>

          {/* Batch Actions */}
          {uuids.length > 0 && (
            <div className="flex flex-wrap gap-2 pt-4 border-t border-gray-200">
              <Button variant="outline" size="sm" onClick={handleCopyAll}>
                <Copy className="w-4 h-4 mr-2" />
                {copyAllSuccess ? '已复制全部' : '复制全部'}
              </Button>
              <Button variant="outline" size="sm" onClick={handleDownload}>
                <Download className="w-4 h-4 mr-2" />
                下载文件
              </Button>
              <Button variant="outline" size="sm" onClick={handleClear}>
                清空列表
              </Button>
            </div>
          )}
        </div>

        {/* Results */}
        {uuids.length > 0 && (
          <div className="bg-white rounded-lg border border-gray-200">
            <div className="p-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">
                生成的 UUID ({uuids.length})
              </h2>
            </div>
            <div className="p-4 space-y-3 max-h-96 overflow-y-auto">
              {uuids.map((uuid, index) => (
                <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <code className="text-sm font-mono text-gray-800 flex-1">
                    {uuid}
                  </code>
                  <Button 
                    variant="outline" 
                    size="sm" 
                    onClick={() => handleCopy(uuid, index)}
                    className="ml-3"
                  >
                    <Copy className="w-4 h-4 mr-1" />
                    {copySuccess[index] ? '已复制' : '复制'}
                  </Button>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Empty State */}
        {uuids.length === 0 && (
          <div className="text-center py-12 bg-gray-50 rounded-lg">
            <RefreshCw className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              还没有生成 UUID
            </h3>
            <p className="text-gray-600 mb-4">
              选择版本和数量，然后点击生成按钮
            </p>
          </div>
        )}

        {/* Info */}
        <div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="p-6 bg-blue-50 rounded-lg">
            <h3 className="font-semibold text-blue-900 mb-3">UUID v4 (推荐)</h3>
            <ul className="text-blue-700 text-sm space-y-1">
              <li>• 基于随机数生成</li>
              <li>• 不包含时间戳或MAC地址</li>
              <li>• 更好的隐私保护</li>
              <li>• 适用于大多数场景</li>
            </ul>
          </div>
          
          <div className="p-6 bg-green-50 rounded-lg">
            <h3 className="font-semibold text-green-900 mb-3">UUID v1</h3>
            <ul className="text-green-700 text-sm space-y-1">
              <li>• 基于时间戳和MAC地址</li>
              <li>• 包含生成时间信息</li>
              <li>• 可以按时间排序</li>
              <li>• 适用于需要时间序列的场景</li>
            </ul>
          </div>
        </div>

        {/* Use Cases */}
        <div className="mt-8 p-6 bg-gray-50 rounded-lg">
          <h3 className="font-semibold text-gray-900 mb-3">常见用途</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-700">
            <ul className="space-y-1">
              <li>• 数据库主键</li>
              <li>• API 请求 ID</li>
              <li>• 文件名唯一标识</li>
              <li>• 会话标识符</li>
            </ul>
            <ul className="space-y-1">
              <li>• 分布式系统节点 ID</li>
              <li>• 消息队列消息 ID</li>
              <li>• 缓存键值</li>
              <li>• 临时资源标识</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  )
}